package com.miaowang.salad.activity;

import org.json.JSONException;
import org.json.JSONObject;

import prj.carmap.mobile.CarmapApplication;
import prj.carmap.mobile.R;
import prj.carmap.mobile.activity.FirstSplashActivity;
import prj.carmap.mobile.activity.MainActivity;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.miaowang.salad.Common;
import com.miaowang.salad.data.OkHttpResponseData;
import com.miaowang.salad.jobqueue.GetCurrentTaskJob;
import com.miaowang.salad.jobqueue.GetIdentifyCodeJob;
import com.miaowang.salad.jobqueue.GetMineInfoJob;
import com.miaowang.salad.jobqueue.JobEvents;
import com.miaowang.salad.jobqueue.LoginJob;
import com.miaowang.salad.util.CheckUtil;
import com.miaowang.salad.util.PrefUtils;
import com.path.android.jobqueue.Job;

import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;

/**
 * 登录页面 2015-08-29
 * 
 * @author weihe
 *
 */
public class UserLoginActivity extends BaseActivity {

	Button submitBtn;
	EditText edtUsername;
	EditText inputValidateNumber;
	private TextView tvGetIdentifyCode;
	private ProgressDialog pd;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main_salad);
		initComponent();
		initControl();
	}

	@Override
	protected void onResume() {
		super.onResume();
		// 判断是否已登录
		boolean hasLogined = PrefUtils.getBoolean(this, Common.PREF_IS_LOGIN,
				false);
		if (hasLogined) {
//			if (Common.debug) {
				Intent intent = new Intent();
				intent.putExtra("hasCurrentTask", 0);
				intent.setClass(UserLoginActivity.this, MainActivity.class);
				startActivity(intent);
				UserLoginActivity.this.finish();
//			} else {
//
//				if (hasLogined) {
//					getCurrentTask(PrefUtils.getString(UserLoginActivity.this,
//							Common.PREF_PHONENUM, ""));
//					finish();
//				}
//			}
		}/*else{
			Intent intent = new Intent();
			intent.putExtra("hasCurrentTask", 0);
			intent.setClass(UserLoginActivity.this, FirstSplashActivity.class);
			startActivity(intent);
			UserLoginActivity.this.finish();
		}*/

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		return super.onOptionsItemSelected(item);
	}

	private void initComponent() {
		edtUsername = (EditText) findViewById(R.id.user_phone_number);
		inputValidateNumber = (EditText) findViewById(R.id.input_validate_number);
		submitBtn = (Button) findViewById(R.id.submit_btn);
		tvGetIdentifyCode = (TextView) findViewById(R.id.tv_get_identifyCode);
	}

	private void initControl() {
		submitBtn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// if (Common.debug) {
				// Intent intent = new Intent(UserLoginActivity.this,
				// MainPageActivity.class);
				// startActivity(intent);
				// return;
				// }
				String userName = edtUsername.getText().toString();
				String password = inputValidateNumber.getText().toString();
				if (userName == null || "".equals(userName)) {
					inputValidateNumber.clearFocus();
					edtUsername.requestFocus();
					edtUsername.setError("请输入用户名");
					return;
				}
				if (password == null || "".equals(password)) {
					edtUsername.clearFocus();
					inputValidateNumber.requestFocus();
					inputValidateNumber.setError("请输入验证码");
					return;
				}

				// 执行登录请求
				login(edtUsername.getText().toString(), inputValidateNumber
						.getText().toString());
			}
		});

		tvGetIdentifyCode.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				getIdentifyCode();
			}
		});
	}

	private void getIdentifyCode() {
		if (CheckUtil.isEmpty(edtUsername.getText().toString())) {
			edtUsername.setError("请输入手机号");
			return;
		}
		if (pd == null) {
			pd = new ProgressDialog(UserLoginActivity.this);
		}
		pd.setTitle("正在获取验证码...");
		pd.show();
		Job job = new GetIdentifyCodeJob(edtUsername.getText().toString());
		CarmapApplication.getInstance().getJobManager().addJobInBackground(job);
	}

	/**
	 * 登录
	 * 
	 * @param phoneNum
	 * @param identifyCode
	 */
	private void login(String phoneNum, String identifyCode) {
		if (pd == null) {
			pd = new ProgressDialog(UserLoginActivity.this);
		}
		pd.setTitle("正在登录...");
		pd.show();
		Job job = new LoginJob(UserLoginActivity.this , phoneNum , identifyCode);
		CarmapApplication.getInstance().getJobManager().addJobInBackground(job);
	}

	private void getCurrentTask(String phoneNum) {
		// 先进行网络请求，查看是否包含未完成的任务
		if (pd == null) {
			pd = new ProgressDialog(UserLoginActivity.this);
		}
		pd.setTitle("正在获取当前任务信息...");
		pd.show();
		Job getCurrentTaskJob = new GetCurrentTaskJob(phoneNum);
		CarmapApplication.getInstance().getJobManager()
				.addJobInBackground(getCurrentTaskJob);
	}

	// EventsBus
	@Subscribe(threadMode = ThreadMode.MainThread)
	public void onEventMainThread(JobEvents.JobSuccess e) {

		OkHttpResponseData msg = (OkHttpResponseData) e.getResult();
		switch (e.getJobCode()) {
		case JobEvents.SEND_PHONE_IDENTIFY_CODE:

			if (pd != null)
				pd.dismiss();
			if (msg != null) {
				dealGetIdentifyCodeResult(msg);
			} else {
				Toast.makeText(UserLoginActivity.this, "获取验证码失败",
						Toast.LENGTH_SHORT).show();
			}

			break;
		case JobEvents.LOGIN:
			if (pd != null)
				pd.dismiss();
			if (msg != null) {
				dealLoginResult(msg);
			} else {
				Toast.makeText(UserLoginActivity.this, "登录失败",
						Toast.LENGTH_SHORT).show();
			}
			break;
//		case JobEvents.GET_CURRENT_TASK:
//			// 清除当前任务信息
//			PrefUtils.putString(UserLoginActivity.this,
//					Common.PREF_CURRENT_TASK, "");
//			if (pd != null)
//				pd.dismiss();
//			if (msg != null) {
//				dealCurrentTaskResult(msg);
//			} else {
//				Toast.makeText(UserLoginActivity.this, "获取当前任务信息失败",
//						Toast.LENGTH_SHORT).show();
//			}
//			break;
		case JobEvents.GET_MY_INFO_BEGIN:
			if (pd != null)
				pd.dismiss();
			if (msg != null) {
				dealGetMineInfoResult(msg);
			} else {
				Toast.makeText(UserLoginActivity.this, "获取我的信息失败",
						Toast.LENGTH_SHORT).show();
			}
			break;
		// default:
		// break;
		}
	}

	@Subscribe(threadMode = ThreadMode.MainThread)
	public void onEventMainThread(JobEvents.JobFailure e) {

		switch (e.getJobCode()) {
		case JobEvents.SEND_PHONE_IDENTIFY_CODE:

			Toast.makeText(UserLoginActivity.this, "网络请求失败-获取验证码",
					Toast.LENGTH_SHORT).show();
			if (pd != null)
				pd.dismiss();

			break;
		case JobEvents.LOGIN:
			Toast.makeText(UserLoginActivity.this, "网络请求失败-登录",
					Toast.LENGTH_SHORT).show();
			if (pd != null)
				pd.dismiss();
			break;
//		case JobEvents.GET_CURRENT_TASK:
//			// 清除当前任务信息
//			PrefUtils.putString(UserLoginActivity.this,
//					Common.PREF_CURRENT_TASK, "");
//			Toast.makeText(UserLoginActivity.this, "网络请求失败-获取当前正在进行任务",
//					Toast.LENGTH_SHORT).show();
//			if (pd != null)
//				pd.dismiss();
//			break;
		case JobEvents.GET_MY_INFO_BEGIN:
			if (pd != null)
				pd.dismiss();
			break;
		// default:
		// break;
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	/**
	 * 处理验证码获取结果
	 * 
	 * @param msg
	 */
	private void dealGetIdentifyCodeResult(OkHttpResponseData msg) {
		int code = msg.getCode();
		if (code == 0) {
			try {
				PrefUtils.putString(UserLoginActivity.this,
						Common.PREF_PHONENUM, edtUsername.getText().toString());
				Log.i(Common.TAG,
						"code " + msg.getCode() + " msg " + msg.getMsg()
								+ " data " + msg.getData());
				String data = msg.getData();
				Toast.makeText(UserLoginActivity.this, msg.getMsg(),
						Toast.LENGTH_SHORT).show();
				// if (CheckUtil.isEmpty(data)) {
				// Toast.makeText(UserLoginActivity.this, "验证码获取失败",
				// Toast.LENGTH_SHORT).show();
				// return;
				// }
				// JSONObject json = new JSONObject(msg.getData());
				// if (json.has("code")) {
				// PrefUtils.putString(UserLoginActivity.this,
				// Common.PREF_TOKEN, json.getString("code"));
				// PrefUtils.putString(UserLoginActivity.this,
				// Common.PREF_PHONENUM, edtUsername.getText()
				// .toString());
				// }

			} catch (Exception e) {
				Toast.makeText(UserLoginActivity.this, "验证码获取失败",
						Toast.LENGTH_SHORT).show();
				e.printStackTrace();
				return;
			}
		} else {
			Toast.makeText(UserLoginActivity.this, msg.getMsg(),
					Toast.LENGTH_SHORT).show();
		}
	}

	/**
	 * 处理登录逻辑
	 * 
	 * @param msg
	 */
	private void dealLoginResult(OkHttpResponseData msg) {
		int code = msg.getCode();
		if (code == 0) {
			try {
				String data = msg.getData();
				if (CheckUtil.isEmpty(data)) {
					Toast.makeText(UserLoginActivity.this, "token获取失败",
							Toast.LENGTH_SHORT).show();
					return;
				}
				JSONObject json = new JSONObject(msg.getData());
				if (json.has("token")) {
					PrefUtils.putString(UserLoginActivity.this,
							Common.PREF_TOKEN, json.getString("token"));
					PrefUtils.putString(UserLoginActivity.this,
							Common.PREF_PHONENUM, edtUsername.getText()
									.toString());
				}

			} catch (JSONException e) {
				Toast.makeText(UserLoginActivity.this, "token获取失败",
						Toast.LENGTH_SHORT).show();
				e.printStackTrace();
				return;
			}
			PrefUtils.putBoolean(UserLoginActivity.this, Common.PREF_IS_LOGIN,
					true);
			if (Common.debug) {
				Intent intent = new Intent(UserLoginActivity.this,
						MainActivity.class);
				intent.putExtra("hasCurrentTask", 0);
				startActivity(intent);
			} else {
				getMineInfoFromServer();
			}
		} else {
			Toast.makeText(UserLoginActivity.this, msg.getMsg(),
					Toast.LENGTH_SHORT).show();
		}
	}

//	private void dealCurrentTaskResult(OkHttpResponseData msg) {
//		int hasCurrent = 0; // 0 无当前任务 1有当前任务
//		int code = msg.getCode();
//		if (code == 0) {
//			try {
//				String data = msg.getData();
//				if (CheckUtil.isEmpty(data)) {
//					Toast.makeText(UserLoginActivity.this, "当前任务获取失败",
//							Toast.LENGTH_SHORT).show();
//					return;
//				}
//				JSONObject json = new JSONObject(msg.getData());
//				if (json.has("service_request")) {
//					String currentTask = json.getString("service_request");
//					if (CheckUtil.isEmpty(currentTask)) {
//						hasCurrent = 0;
//					} else {
//						PrefUtils.putString(UserLoginActivity.this,
//								Common.PREF_CURRENT_TASK, currentTask);
//						hasCurrent = 1;
//					}
//
//				}else{
//					Toast.makeText(UserLoginActivity.this, "当前任务获取失败",
//							Toast.LENGTH_SHORT).show();
//					return;
//				}
//
//			} catch (JSONException e) {
//				Toast.makeText(UserLoginActivity.this, "当前任务获取失败",
//						Toast.LENGTH_SHORT).show();
//				e.printStackTrace();
//				return;
//			}
//			Intent intent = new Intent(UserLoginActivity.this,
//					MainPageActivity.class);
//			intent.putExtra("hasCurrentTask", hasCurrent);
//			startActivity(intent);
//		} else {
//			Toast.makeText(UserLoginActivity.this, msg.getMsg(),
//					Toast.LENGTH_SHORT).show();
//		}
//	}
	
	/**
	 * 获取个人信息
	 */
	private void getMineInfoFromServer() {
		if (pd == null) {
			pd = new ProgressDialog(UserLoginActivity.this);
		}
		pd.setTitle("正在获取我的信息...");
		pd.show();
		Job job = new GetMineInfoJob(0);
		CarmapApplication.getInstance().getJobManager().addJobInBackground(job);
	}

	
	private void dealGetMineInfoResult(OkHttpResponseData msg){
		
		if (msg != null) {
			if (msg.getCode() == 0) {
				Toast.makeText(UserLoginActivity.this, msg.getMsg(),
						Toast.LENGTH_SHORT).show();
				if (!CheckUtil.isEmpty(msg.getData())) {
					try {
						JSONObject json = new JSONObject(msg.getData());
						if (json.has("user")) {
							String userString = json.getString("user");
							if (!CheckUtil.isEmpty(userString)) {
								// 将我的信息保存到缓存中
								PrefUtils.putString(UserLoginActivity.this,
										Common.PREF_MY_INFO, userString);
							} else {
								Toast.makeText(UserLoginActivity.this,
										"我的信息获取失败", Toast.LENGTH_SHORT)
										.show();
								return;
							}
						} else {
							Toast.makeText(UserLoginActivity.this,
									"我的信息获取失败", Toast.LENGTH_SHORT).show();
							return;
						}
					} catch (JSONException e1) {
						e1.printStackTrace();
						return;
					}
					Intent intent = new Intent(UserLoginActivity.this,
							MainActivity.class);
					intent.putExtra("hasCurrentTask", 0);
					startActivity(intent);
					
//					getCurrentTask(edtUsername.getText().toString());
				} else {
					PrefUtils.putString(UserLoginActivity.this,
							Common.PREF_MY_INFO, "");//无个人信息
					Toast.makeText(UserLoginActivity.this, msg.getMsg(),
							Toast.LENGTH_SHORT).show();
				}

			} else {
				Toast.makeText(UserLoginActivity.this, msg.getMsg(),
						Toast.LENGTH_SHORT).show();
			}
		} else {
			Toast.makeText(UserLoginActivity.this, "网络请求异常",
					Toast.LENGTH_SHORT).show();
		}
	}
}
